﻿using System;
using System.IO;
using System.Text.Json;

namespace FlyingEye.SaveInfoServices
{
    public static class JsonConfigFileHelper
    {
        public static TModel Read<TModel>(Stream stream) where TModel : class, new()
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            return JsonSerializer.Deserialize<TModel>(bytes) ?? throw new InvalidOperationException($"{typeof(TModel).Name}对象反序列化异常！");
        }

        public static void Write<TModel>(Stream stream, TModel model) where TModel : class, new()
        {
            stream.SetLength(0); // 清空文件流内容。
            JsonSerializer.Serialize(new Utf8JsonWriter(stream), model);
            stream.Flush();
        }
    }
}
